/**
 * 
 */
package org.pandazxx.picasamanager.launch;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.pandazxx.picasamanager.PicasaException;
import org.pandazxx.picasamanager.client.PicasawebClient;
import org.pandazxx.picasamanager.helper.Arguments;
import org.pandazxx.picasamanager.io.InputStreamIntercepter;
import org.pandazxx.picasamanager.io.TransferMonitor;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.MediaStreamSource;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoData;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.TagData;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

/**
 * @author pandazxx
 * 
 */
public class Launcher {
	private static final Logger logger = Logger.getLogger(Launcher.class);

	private PicasawebClient client;

	private Arguments arguments;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int exitCode;
		PropertyConfigurator.configure(Launcher.class
				.getResource("/log4j.property"));
		Launcher launcher = new Launcher();

		exitCode = launcher.run(args);

		System.exit(exitCode);
	}

	private static void loadSystemPropertys() {
		File propFile = new File("picasa-uploader.property");
		if (propFile.canRead()) {
			logger.debug("Loading property file " + propFile.getAbsolutePath());
		}
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(propFile));
			System.setProperties(prop);
			StringWriter stringWriter = new StringWriter();
			logger.debug("Properies loaded:");
			for (Map.Entry entry : System.getProperties().entrySet()) {
				logger.debug(entry.getKey() + "=" + entry.getValue());
			}
		} catch (Exception e) {
			logger.warn("Cannot load property file "
					+ propFile.getAbsolutePath(), e);
		}
	}

	private void listAlbum() throws AuthenticationException,
			MalformedURLException, IOException, ServiceException,
			PicasaException {
		AlbumEntry albumEntry = getAlbumEntry();
		AlbumFeed albumFeed = albumEntry.getFeed();
		logger
				.info("Totally " + albumFeed.getPhotoEntries().size()
						+ " photos");
		for (PhotoEntry photo : albumFeed.getPhotoEntries()) {
			System.out.println(photo.getTitle().getPlainText());

		}
	}

	private void uploadImage() {
		try {
			AlbumEntry albumEntry = getAlbumEntry();

			// URL albumPostUrl = new URL(
			// "http://picasaweb.google.com/data/feed/api/user/"
			// + arguments.getOperUsername() + "/albumid/"
			// + arguments.getAlbumName() + "#");
			for (String filename : arguments.getFilenameList()) {
				logger.info("Uploading photo " + filename);
				PhotoEntry myPhoto = new PhotoEntry();
				myPhoto.setTitle(new PlainTextConstruct(filename));
				myPhoto.setClient("Picasa Uploader");

				// MediaFileSource myMedia = new MediaFileSource(
				// new File(filename), "image/jpeg");
				File file = new File(filename);
				MediaStreamSource myMedia = new MediaStreamSource(
						new InputStreamIntercepter(new FileInputStream(file))
								.addListener(new TransferMonitor(1000, file
										.length())), "image/jpeg");
				myPhoto.setMediaSource(myMedia);

				AlbumFeed albumFeed = albumEntry.getFeed(PhotoData.KIND,
						TagData.KIND);
				albumFeed.insert(myPhoto);
			}

		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @return
	 * @throws ServiceException 
	 * @throws IOException 
	 * @throws AuthenticationException
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws ServiceException
	 * @throws PicasaException
	 */
	private AlbumEntry getAlbumEntry() throws IOException, ServiceException {
//		PicasawebService myService = new PicasawebService(
//				"pandazxx-picasauploader-1");
		//
		// myService.setUserCredentials(arguments.getLoginUsername(), arguments
		// .getLoginPassword());
		// URL feedUrl = new
		// URL("http://picasaweb.google.com/data/feed/api/user/"
		// + arguments.getOperUsername() + "?kind=album");
		//
		// UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);
		//
		 AlbumEntry albumEntry = null;
		//
		// for (AlbumEntry entry : myUserFeed.getAlbumEntries()) {
		// logger.debug("Checking album: " + entry.getName());
		// logger.debug("Checking album: " + entry.getId());
		// logger.debug("Checking album: " + entry.getNickname());
		// logger.debug(entry.getDescription().toString());
		// logger.debug(entry.getTitle().getPlainText());
		//
		// if (entry.getTitle().getPlainText()
		// .equals(arguments.getAlbumName())) {
		// albumEntry = entry;
		// logger.info("Album " + entry.getTitle().getPlainText()
		// + " matched!");
		//
		// break;
		// }
		// }
		// if (albumEntry == null)
		// throw new PicasaException("Album " + arguments.getAlbumName()
		// + " is not exist!");
		for (AlbumEntry e : client.getAlbums()) {
			if (e.getTitle().getPlainText().equals(arguments.getAlbumName())) {
				albumEntry = e;
			}
		}
		
		return albumEntry;
	}

	private int run(String[] args) {
		loadSystemPropertys();

		arguments = Arguments.getArguments(args);

		if (arguments == null) {
			return 1;
		}
		try {
			PicasawebService myService = new PicasawebService(
					"pandazxx-picasauploader-1");
			client = new PicasawebClient(myService);

			if (arguments.getOperation() == Arguments.Operation.Upload) {
				uploadImage();
			} else if (arguments.getOperation() == Arguments.Operation.List) {
				listAlbum();
			}

		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PicasaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}

}
